#include <semaphore.h>
#include <pthread.h>
#include <string.h>
#include <stdbool.h>
#include "messageProcessor.h"
static sem_t full_sem, empty_sem;
static pthread_mutex_t mutex_writer;
static int mQueue_head=0;
static int mQueue_tail=0;
static bool messageIsStart=false;
static struct messageQueue queue[MAX_QUEUE_SIZE];
void initQueue(void){
	pthread_mutex_init(&mutex_writer,NULL);
	sem_init(&full_sem,0,MAX_QUEUE_SIZE);
	sem_init(&empty_sem,0,0);
	messageIsStart=true;
}
int writeMessage(unsigned char *buf, int size, int sendfd){
	if(messageIsStart==false) return -1;
	if(size>MESSAGE_SIZE) return -1;
	sem_wait(&full_sem);
	pthread_mutex_lock(&mutex_writer);
	/*Start Critical Section*/
	queue[mQueue_tail].size=size;
	queue[mQueue_tail].send_fd=sendfd;
	memmove(queue[mQueue_tail].buf,buf,size);
	++mQueue_tail;
	if(mQueue_tail==MAX_QUEUE_SIZE) mQueue_tail=0;
	/*End Critical Section*/
	pthread_mutex_unlock(&mutex_writer);
	sem_post(&empty_sem);
	return size;
}

//this function access only one thread.
struct messageQueue readMessage(void){
	if(messageIsStart==false){
		struct messageQueue fail={0,};
		return fail;
	}	
	sem_wait(&empty_sem);
	struct messageQueue msg=queue[mQueue_head];
	++mQueue_head;
	if(mQueue_head==MAX_QUEUE_SIZE) mQueue_head=0;
	sem_post(&full_sem);
	return msg;
}
